from rest_framework import serializers
from .models import *
from django.forms import ValidationError
import re

class UserSer(serializers.ModelSerializer):
    # write_only 序列化输入
    # trim_whitespace 取出两边空格
    password = serializers.CharField(write_only=True,trim_whitespace=True,max_length=50,min_length=5)

    # 局部校验
    # # 用户名
    # def validated_name(self,username):
    #     if re.findall(r'^[A-Z][a-zA-Z0-9_]{5,9}$',username):
    #         return username
    #     else:
    #         raise ValidationError('职责名称不匹配')
    #
    # # 密码
    # def validated_password(self,password):
    #     if re.findall(r'^[A-Z]+[a-zA-Z0-9_]+[a-zA-Z0-9]+$',password):
    #         return password
    #     else:
    #         raise ValidationError('密码不匹配')
    #
    # # 手机号
    # def validated_phone(self,phone):
    #     if re.findall(r'^13[0-9]{9}$',phone):
    #         return phone
    #     else:
    #         raise ValidationError('密码不匹配')
    # # 邮箱
    # def validated_phone(self,phone):
    #     if re.findall(r'^[0-9][a-zA-Z0-9_]{5,19}@qq\.com$',phone):
    #         return phone
    #     else:
    #         raise ValidationError('密码不匹配')


    class Meta:
        model = User
        fields = ['id','username','phone','email','date_joined','last_login','password']
        # write_only 序列化输出
        read_only_fields = ['id','last_login','password']


    # def update(self, instance, validated_data):
    #     instance.username = validated_data.get('username')
    #     instance.set_password = validated_data.get('password')
    #     instance.phone = validated_data.get('phone')
    #     instance.email = validated_data.get('email')
    #     instance.save()
    #     return instance


# 增加用户图片的序列化器
class UserImageSer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    user_username = serializers.SerializerMethodField(read_only=True)

    def get_user_username(self,obj):
        return obj.user.username

    class Meta:
        model = UserImage
        fields = '__all__'
        read_only_fields = [id]